package com.ruoyi.bantong.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.ruoyi.bantong.constant.BanTongConstants;
import com.ruoyi.bantong.domain.*;
import com.ruoyi.bantong.mapper.*;
import com.ruoyi.bantong.service.IBtUserAccountRecordService;
import com.ruoyi.common.core.domain.entity.BtUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.bantong.service.IBtPlacecardPoolService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 席位池Service业务层处理
 * 
 * @author laohei
 * @date 2021-01-24
 */
@Service
public class BtPlacecardPoolServiceImpl implements IBtPlacecardPoolService 
{
    @Autowired
    private BtPlacecardPoolMapper btPlacecardPoolMapper;

    @Autowired
    private BtPlacecardPoolDetailsMapper btPlacecardPoolDetailsMapper;

    @Autowired
    private BtUserMapper btUserMapper;

    @Autowired
    private BtUserLevelMapper btUserLevelMapper;

    @Autowired
    private BtPlacecardConfigMapper configMapper;

    @Autowired
    private IBtUserAccountRecordService userAccountRecordService;

    /**
     * 查询席位池
     * 
     * @param ppId 席位池ID
     * @return 席位池
     */
    @Override
    public BtPlacecardPool selectBtPlacecardPoolById(Integer ppId)
    {
        BtPlacecardPool pool = btPlacecardPoolMapper.selectBtPlacecardPoolById(ppId);
        BtPlacecardPoolDetails details = new BtPlacecardPoolDetails();
        details.setPpId(pool.getPpId());
        List<BtPlacecardPoolDetails> btPlacecardPoolDetails = btPlacecardPoolDetailsMapper.selectBtPlacecardPoolDetailsList(details);
        pool.setDetailsList(btPlacecardPoolDetails);
        return pool;
    }

    /**
     * 查询席位池列表
     * 
     * @param btPlacecardPool 席位池
     * @return 席位池
     */
    @Override
    public List<BtPlacecardPool> selectBtPlacecardPoolList(BtPlacecardPool btPlacecardPool)
    {
        return btPlacecardPoolMapper.selectBtPlacecardPoolList(btPlacecardPool);
    }

    /**
     * 查询 全部级别 席位池用户状态
     *
     * @param userId
     * @return 席位池集合
     */
    @Override
    public List<Map<String,Object>> selectBtPlacecardPoolAllLevel(Integer userId) {
        return btPlacecardPoolMapper.selectBtPlacecardPoolAllLevel(userId);
    }

    /**
     * 新增席位池
     * 
     *
     * @return 结果
     */
    @Override
    @Transactional
    public BtPlacecardPool insertBtPlacecardPool(Integer userLevel) throws Exception
    {
        Integer btUserId = SecurityUtils.getBtUserId();//当前登录用户
        BtUser loginBtUser = btUserMapper.selectBtUserById(btUserId);
//        Integer userLevel = loginBtUser.getUserLevel(); //用户等级
        BtPlacecardPool result = null;
        //判断是否 正在参加开奖
        result = btPlacecardPoolMapper.selectBtPlacecardPoolByUserId(loginBtUser.getUserId(), userLevel);
        if(StringUtils.isNull(result)){ //当前没有参加 席位
            //判断余额
            BtUser btUser = btUserMapper.selectBtUserById(loginBtUser.getUserId());
            btUser.setUserLevel(userLevel); //用户等级赋值当前等级
            BigDecimal btBean = btUser.getBtBean(); //金豆余额
            BtUserLevel btUserLevel = btUserLevelMapper.selectBtUserLevelByLevel(userLevel);
            BigDecimal earnestMoney = BigDecimal.valueOf(btUserLevel.getEarnestMoney()); //保证金
            if(earnestMoney.compareTo(btBean) == 1){
                throw new CustomException("金豆不足！");
            }
            BtPlacecardConfig btPlacecardConfig = configMapper.selectBtPlacecardConfigById(userLevel);
            if(StringUtils.isNull(btPlacecardConfig)){
                throw new CustomException("您的等级暂未设置具体玩法！");
            }
            BtPlacecardPool btPlacecardPool = btPlacecardPoolMapper.selectBtPlacecardPoolByLevel(userLevel);//当前等级可用的席位池
            //加入席位池
            result = this.addBtPlacecardPool(btPlacecardPool, btUser, btUserLevel);
            //开奖
            if(!StringUtils.isNull(btPlacecardPool)){
                Integer playCount = btPlacecardPool.getPlayCount();//玩法人数
                Integer total = btPlacecardPool.getTotal(); //已加入人数
                if((playCount) ==  total){ //当前是最后一名加入玩家  开奖
                    this.openPlacecardPool(btPlacecardPool);
                }
            }
        }
        BtPlacecardPoolDetails details = new BtPlacecardPoolDetails();
        details.setPpId(result.getPpId());
        List<BtPlacecardPoolDetails> btPlacecardPoolDetails = btPlacecardPoolDetailsMapper.selectBtPlacecardPoolDetailsList(details);
        result.setDetailsList(btPlacecardPoolDetails);
        return result;
    }


    /**
     * 退出席位池
     * @return 结果
     */
    @Override
    @Transactional
    public int outBtPlacecardPool(Integer userLevel) throws Exception{
        Integer btUserId = SecurityUtils.getBtUserId();//当前登录用户
        BtUser btUser = btUserMapper.selectBtUserById(btUserId);
//        Integer userLevel = btUser.getUserLevel(); //用户等级
        BtPlacecardPool pool = null;
        //判断是否 正在参加开奖
        pool = btPlacecardPoolMapper.selectBtPlacecardPoolByUserId(btUser.getUserId(), userLevel);
        Integer status = pool.getStatus();
        if(status != 0){ //不是未开奖状态
            throw  new RuntimeException("开奖中请勿退出！");
        }
        //删除
        int i = btPlacecardPoolDetailsMapper.deleteBtPlacecardPoolDetailsByUserId(pool.getPpId(), btUser.getUserId());
        //修改参加人数
        BtPlacecardPool tempPool = new BtPlacecardPool();
        tempPool.setPpId(pool.getPpId());
        tempPool.setTotal(pool.getTotal() - 1);
        btPlacecardPoolMapper.updateBtPlacecardPool(tempPool);
        //退回余额
        userAccountRecordService.updataUserAccount(btUserId,BigDecimal.valueOf(pool.getEarnestMoney()),BigDecimal.ZERO,
                pool.getPpId(),"bt_placecard_pool","in",2);
        return i;
    }

    //加入席位
    private BtPlacecardPool addBtPlacecardPool(BtPlacecardPool btPlacecardPool,BtUser loginBtUser ,BtUserLevel btUserLevel) throws Exception
    {
        if(StringUtils.isNull(btPlacecardPool)){
            btPlacecardPool = new BtPlacecardPool();
            btPlacecardPool.setCreateTime(DateUtils.getNowDate());
            btPlacecardPool.setLevel(loginBtUser.getUserLevel());
            btPlacecardPool.setPpCode(DateUtils.dateTime());
            btPlacecardPool.setTotal(1);
            btPlacecardPoolMapper.insertBtPlacecardPool(btPlacecardPool);
            BtPlacecardPoolDetails details = new BtPlacecardPoolDetails();
            details.setPpId(btPlacecardPool.getOsid());
            details.setUserId(loginBtUser.getUserId());
            details.setCreateTime(DateUtils.getNowDate());
            details.setEarnestMoney(btUserLevel.getEarnestMoney());
            btPlacecardPoolDetailsMapper.insertBtPlacecardPoolDetails(details);
            btPlacecardPool.setPpCode("BTP"+DateUtils.dateTime() + btPlacecardPool.getOsid());
            btPlacecardPool.setPpId(btPlacecardPool.getOsid());
            btPlacecardPoolMapper.updateBtPlacecardPool(btPlacecardPool);
            //扣除余额
            userAccountRecordService.updataUserAccount(loginBtUser.getUserId(),BigDecimal.valueOf(btUserLevel.getEarnestMoney()),BigDecimal.ZERO,
                                                      btPlacecardPool.getOsid(),"bt_placecard_pool","out",1);
            btPlacecardPool.setPpId(btPlacecardPool.getOsid());
            return btPlacecardPool;
        }else {
            BtPlacecardPoolDetails details = new BtPlacecardPoolDetails();
            details.setPpId(btPlacecardPool.getPpId());
            details.setUserId(loginBtUser.getUserId());
            details.setCreateTime(DateUtils.getNowDate());
            details.setEarnestMoney(btUserLevel.getEarnestMoney());
            btPlacecardPoolDetailsMapper.insertBtPlacecardPoolDetails(details);
            btPlacecardPool.setTotal(btPlacecardPool.getTotal() + 1);
            btPlacecardPoolMapper.updateBtPlacecardPool(btPlacecardPool);

            //扣除余额
            userAccountRecordService.updataUserAccount(loginBtUser.getUserId(),BigDecimal.valueOf(btUserLevel.getEarnestMoney()),BigDecimal.ZERO,
                    btPlacecardPool.getPpId(),"bt_placecard_pool","out",1);
            return btPlacecardPool;
        }
    }

    private void openPlacecardPool(BtPlacecardPool btPlacecardPool){
        BtPlacecardPoolDetails details = new BtPlacecardPoolDetails();
        details.setPpdId(btPlacecardPool.getPpId());
        List<BtPlacecardPoolDetails> btPlacecardPoolDetails = btPlacecardPoolDetailsMapper.selectBtPlacecardPoolDetailsListForOpen(btPlacecardPool.getPpId());
        for (int i = btPlacecardPool.getWinCount(); i >=1; i--) {
            Random random = new Random();
            Math.random();
            //在数组大小之间产生一个随机数 j
            int j = random.nextInt(btPlacecardPoolDetails.size() == 1 ? 1 : btPlacecardPoolDetails.size());
            //取得list 中下标为j 的数据存储到 listRandom 中
            BtPlacecardPoolDetails detailsWin = btPlacecardPoolDetails.get(j);
            detailsWin.setResult(1);//中奖标志
            detailsWin.setUpdateTime(DateUtils.getNowDate());
            btPlacecardPoolDetailsMapper.updateBtPlacecardPoolDetails(detailsWin);
            //把已取到的数据移除,避免下次再次取到出现重复
            btPlacecardPoolDetails.remove(j);
        }
        btPlacecardPool.setStatus(1);
        btPlacecardPool.setOpenTime(DateUtils.getNowDate());
        btPlacecardPool.setPublishTime(DateUtils.dateAddMinutes(null,btPlacecardPool.getOpenInterval()));
        btPlacecardPoolMapper.updateBtPlacecardPool(btPlacecardPool);
    }

    /**
     * 修改席位池
     * 
     * @param btPlacecardPool 席位池
     * @return 结果
     */
    @Override
    public int updateBtPlacecardPool(BtPlacecardPool btPlacecardPool)
    {
        btPlacecardPool.setUpdateTime(DateUtils.getNowDate());
        return btPlacecardPoolMapper.updateBtPlacecardPool(btPlacecardPool);
    }

    /**
     * 批量删除席位池
     * 
     * @param ppIds 需要删除的席位池ID
     * @return 结果
     */
    @Override
    public int deleteBtPlacecardPoolByIds(Integer[] ppIds)
    {
        return btPlacecardPoolMapper.deleteBtPlacecardPoolByIds(ppIds);
    }

    /**
     * 删除席位池信息
     * 
     * @param ppId 席位池ID
     * @return 结果
     */
    @Override
    public int deleteBtPlacecardPoolById(Integer ppId)
    {
        return btPlacecardPoolMapper.deleteBtPlacecardPoolById(ppId);
    }

    @Override
    public int updateBtPlacecardPoolPublishTime(Integer ppId) {
        return btPlacecardPoolMapper.updateBtPlacecardPoolPublishTime(ppId);
    }

    @Override
    public BtPlacecardPool ifPool() throws Exception {
        Integer btUserId = SecurityUtils.getBtUserId();
        BtUser btUser = btUserMapper.selectBtUserById(btUserId);
        BtPlacecardPool result = null;
        //判断是否 正在参加开奖
        result = btPlacecardPoolMapper.selectBtPlacecardPoolByUserId(btUserId, btUser.getUserLevel());
        return result;
    }
}
